Merge iwtransclusion branch into trunk
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * File for BacklinkCache class
4 * @file
5 */
6
7 /**
8 * Class for fetching backlink lists, approximate backlink counts and
9 * partitions. This is a shared cache.
10 *
11 * Instances of this class should typically be fetched with the method
12 * $title->getBacklinkCache().
13 *
14 * Ideally you should only get your backlinks from here when you think
15 * there is some advantage in caching them. Otherwise it's just a waste
16 * of memory.
17 *
18 * Introduced by r47317
19 *
20 * @internal documentation reviewed on 18 Mar 2011 by hashar
21 *
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Ashar Voultoiz
26 */
27 class BacklinkCache {
28
29 /**
30 * Multi dimensions array representing batches. Keys are:
31 * > (string) links table name
32 * > 'numRows' : Number of rows for this link table
33 * > 'batches' : array( $start, $end )
34 *
35 * @see BacklinkCache::partitionResult()
36 *
37 * Cleared with BacklinkCache::clear()
38 */
39 protected $partitionCache = array();
40
41 /**
42 * Contains the whole links from a database result.
43 * This is raw data that will be partitioned in $partitionCache
44 *
45 * Initialized with BacklinkCache::getLinks()
46 * Cleared with BacklinkCache::clear()
47 */
48 protected $fullResultCache = array();
49
50 /**
51 * Local copy of a database object.
52 *
53 * Accessor: BacklinkCache::getDB()
54 * Mutator : BacklinkCache::setDB()
55 * Cleared with BacklinkCache::clear()
56 */
57 protected $db;
58
59 /**
60 * Local copy of a Title object
61 */
62 protected $title;
63
64 const CACHE_EXPIRY = 3600;
65
66 /**
67 * Create a new BacklinkCache
68 * @param Title $title : Title object to create a backlink cache for.
69 */
70 function __construct( $title ) {
71 $this->title = $title;
72 }
73
74 /**
75 * Serialization handler, diasallows to serialize the database to prevent
76 * failures after this class is deserialized from cache with dead DB
77 * connection.
78 */
79 function __sleep() {
80 return array( 'partitionCache', 'fullResultCache', 'title' );
81 }
82
83 /**
84 * Clear locally stored data and database object.
85 */
86 public function clear() {
87 $this->partitionCache = array();
88 $this->fullResultCache = array();
89 unset( $this->db );
90 }
91
92 /**
93 * Set the Database object to use
94 *
95 * @param $db DatabaseBase
96 */
97 public function setDB( $db ) {
98 $this->db = $db;
99 }
100
101 /**
102 * Get the slave connection to the database
103 * When non existing, will initialize the connection.
104 * @return Database object
105 */
106 protected function getDB() {
107 if ( !isset( $this->db ) ) {
108 $this->db = wfGetDB( DB_SLAVE );
109 }
110
111 return $this->db;
112 }
113
114 /**
115 * Get the backlinks for a given table. Cached in process memory only.
116 * @param $table String
117 * @param $startId Integer or false
118 * @param $endId Integer or false
119 * @return TitleArrayFromResult
120 */
121 public function getLinks( $table, $startId = false, $endId = false ) {
122 wfProfileIn( __METHOD__ );
123
124 $fromField = $this->getPrefix( $table ) . '_from';
125
126 if ( $startId || $endId ) {
127 // Partial range, not cached
128 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
129 $conds = $this->getConditions( $table );
130
131 // Use the from field in the condition rather than the joined page_id,
132 // because databases are stupid and don't necessarily propagate indexes.
133 if ( $startId ) {
134 $conds[] = "$fromField >= " . intval( $startId );
135 }
136
137 if ( $endId ) {
138 $conds[] = "$fromField <= " . intval( $endId );
139 }
140
141 $res = $this->getDB()->select(
142 array( $table, 'page' ),
143 array( 'page_namespace', 'page_title', 'page_id' ),
144 $conds,
145 __METHOD__,
146 array(
147 'STRAIGHT_JOIN',
148 'ORDER BY' => $fromField
149 ) );
150 $ta = TitleArray::newFromResult( $res );
151
152 wfProfileOut( __METHOD__ );
153 return $ta;
154 }
155
156 // @todo FIXME: Make this a function?
157 if ( !isset( $this->fullResultCache[$table] ) ) {
158 wfDebug( __METHOD__ . ": from DB\n" );
159 $res = $this->getDB()->select(
160 array( $table, 'page' ),
161 array( 'page_namespace', 'page_title', 'page_id' ),
162 $this->getConditions( $table ),
163 __METHOD__,
164 array(
165 'STRAIGHT_JOIN',
166 'ORDER BY' => $fromField,
167 ) );
168 $this->fullResultCache[$table] = $res;
169 }
170
171 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
172
173 wfProfileOut( __METHOD__ );
174 return $ta;
175 }
176
177 /**
178 * Get the distant backtemplatelinks for the table globaltemplatelinks. Cached in process memory only.
179 * @return ResultWrapper list of distant pages that use the local title
180 */
181 public function getDistantTemplateLinks( ) {
182 global $wgGlobalDatabase, $wgLocalInterwiki;
183
184 $dbr = $dbr = wfGetDB( DB_SLAVE, array(), $wgGlobalDatabase );
185 $res = $dbr->select(
186 array( 'globaltemplatelinks', 'globalinterwiki' ),
187 array( 'gtl_from_wiki', 'gtl_from_page', 'gtl_from_title', 'giw_prefix' ),
188 array( 'gtl_to_prefix' => $wgLocalInterwiki, 'gtl_to_title' => $this->title->getDBkey( ) ),
189 __METHOD__,
190 null,
191 array( 'gtl_from_wiki = giw_wikiid' )
192 );
193 return $res;
194 }
195
196 /**
197 * Get the field name prefix for a given table
198 * @param $table String
199 */
200 protected function getPrefix( $table ) {
201 static $prefixes = array(
202 'pagelinks' => 'pl',
203 'imagelinks' => 'il',
204 'categorylinks' => 'cl',
205 'templatelinks' => 'tl',
206 'redirect' => 'rd',
207 'globaltemplatelinks' => 'gtl',
208 );
209
210 if ( isset( $prefixes[$table] ) ) {
211 return $prefixes[$table];
212 } else {
213 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
214 }
215 }
216
217 /**
218 * Get the SQL condition array for selecting backlinks, with a join
219 * on the page table.
220 * @param $table String
221 */
222 protected function getConditions( $table ) {
223 $prefix = $this->getPrefix( $table );
224
225 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
226 // they could be moved up for nicer case statements
227 switch ( $table ) {
228 case 'pagelinks':
229 case 'templatelinks':
230 $conds = array(
231 "{$prefix}_namespace" => $this->title->getNamespace(),
232 "{$prefix}_title" => $this->title->getDBkey(),
233 "page_id={$prefix}_from"
234 );
235 break;
236 case 'redirect':
237 $conds = array(
238 "{$prefix}_namespace" => $this->title->getNamespace(),
239 "{$prefix}_title" => $this->title->getDBkey(),
240 $this->getDb()->makeList( array(
241 "{$prefix}_interwiki = ''",
242 "{$prefix}_interwiki is null",
243 ), LIST_OR ),
244 "page_id={$prefix}_from"
245 );
246 break;
247 case 'imagelinks':
248 $conds = array(
249 'il_to' => $this->title->getDBkey(),
250 'page_id=il_from'
251 );
252 break;
253 case 'categorylinks':
254 $conds = array(
255 'cl_to' => $this->title->getDBkey(),
256 'page_id=cl_from',
257 );
258 break;
259 default:
260 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
261 }
262
263 return $conds;
264 }
265
266 /**
267 * Get the approximate number of backlinks
268 * @param $table String
269 * @return integer
270 */
271 public function getNumLinks( $table ) {
272 if ( isset( $this->fullResultCache[$table] ) ) {
273 return $this->fullResultCache[$table]->numRows();
274 }
275
276 if ( isset( $this->partitionCache[$table] ) ) {
277 $entry = reset( $this->partitionCache[$table] );
278 return $entry['numRows'];
279 }
280
281 $titleArray = $this->getLinks( $table );
282
283 return $titleArray->count();
284 }
285
286 /**
287 * Partition the backlinks into batches.
288 * Returns an array giving the start and end of each range. The first
289 * batch has a start of false, and the last batch has an end of false.
290 *
291 * @param $table String: the links table name
292 * @param $batchSize Integer
293 * @return Array
294 */
295 public function partition( $table, $batchSize ) {
296
297 // 1) try partition cache ...
298
299 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
300 wfDebug( __METHOD__ . ": got from partition cache\n" );
301 return $this->partitionCache[$table][$batchSize]['batches'];
302 }
303
304 $this->partitionCache[$table][$batchSize] = false;
305 $cacheEntry =& $this->partitionCache[$table][$batchSize];
306
307 // 2) ... then try full result cache ...
308
309 if ( isset( $this->fullResultCache[$table] ) ) {
310 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
311 wfDebug( __METHOD__ . ": got from full result cache\n" );
312
313 return $cacheEntry['batches'];
314 }
315
316 // 3) ... fallback to memcached ...
317
318 global $wgMemc;
319
320 $memcKey = wfMemcKey(
321 'backlinks',
322 md5( $this->title->getPrefixedDBkey() ),
323 $table,
324 $batchSize
325 );
326
327 $memcValue = $wgMemc->get( $memcKey );
328
329 if ( is_array( $memcValue ) ) {
330 $cacheEntry = $memcValue;
331 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
332
333 return $cacheEntry['batches'];
334 }
335
336
337 // 4) ... finally fetch from the slow database :(
338
339 $this->getLinks( $table );
340 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
341 // Save to memcached
342 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
343
344 wfDebug( __METHOD__ . ": got from database\n" );
345 return $cacheEntry['batches'];
346 }
347
348 /**
349 * Partition a DB result with backlinks in it into batches
350 * @param $res ResultWrapper database result
351 * @param $batchSize integer
352 * @return array @see
353 */
354 protected function partitionResult( $res, $batchSize ) {
355 $batches = array();
356 $numRows = $res->numRows();
357 $numBatches = ceil( $numRows / $batchSize );
358
359 for ( $i = 0; $i < $numBatches; $i++ ) {
360 if ( $i == 0 ) {
361 $start = false;
362 } else {
363 $rowNum = intval( $numRows * $i / $numBatches );
364 $res->seek( $rowNum );
365 $row = $res->fetchObject();
366 $start = $row->page_id;
367 }
368
369 if ( $i == $numBatches - 1 ) {
370 $end = false;
371 } else {
372 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
373 $res->seek( $rowNum );
374 $row = $res->fetchObject();
375 $end = $row->page_id - 1;
376 }
377
378 # Sanity check order
379 if ( $start && $end && $start > $end ) {
380 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
381 }
382
383 $batches[] = array( $start, $end );
384 }
385
386 return array( 'numRows' => $numRows, 'batches' => $batches );
387 }
388 }